package com.SouthernWall_404.AgeRight.Common.API.MissionAPI;

import com.SouthernWall_404.AgeRight.Common.API.Capability.Missions;
import com.SouthernWall_404.AgeRight.Common.API.Capability.Provider.MissionsProvider;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;

import java.util.ArrayList;
import java.util.List;

public class MainMissionInfo extends AbstractMissionInfo{

    /*
    主任务栏
    用于包含多项任务内容
    -需要包含奖励内容
    -需要多项任务的存储、
     */

    public RewardInfo rewardInfo=new RewardInfo(ItemStack.EMPTY);
    public List<AbstractMissionInfo> missions=new ArrayList<>();

    public MainMissionInfo(RewardInfo rewardInfo, List<AbstractMissionInfo> missions,String describe) {
        super(missions.size(),MissionType.MAIN,describe);//进度总数就是需要完成的子任务

        this.missions=missions;//所有的子任务
        this.rewardInfo=rewardInfo;//任务奖励
    }

    // 无参构造函数用于NBT加载
    public MainMissionInfo() {
        super(0, MissionType.MAIN,"");
    }

    //检查函数，每有变化执行一次
    @Override
    public void check(Player player) {

        int currentFinished=0;
        for(AbstractMissionInfo missionInfo:missions)
        {
            if(missionInfo.isFininshed)
            {
                currentFinished++;
            }
        }
        setProgress(currentFinished);

        super.check(player);

        if(isFininshed)
        {
            player.displayClientMessage(
                    net.minecraft.network.chat.Component.literal("任务完成!")
                            .withStyle(net.minecraft.ChatFormatting.GREEN),
                    true
            );
            Missions missions1=player.getCapability(MissionsProvider.MISSIONS_CAPABILITY).orElse(null);
            if(missions1!=null)
            {
                missions1.completeMission(this,player);
            }

            // 给玩家奖励
            if (rewardInfo != null) {
                rewardInfo.giveReward(player);
            }
        }
    }

    @Override
    public void checkKill(LivingEntity livingEntity, Player player) {
        for(AbstractMissionInfo missionInfo:missions)
        {
            missionInfo.checkKill(livingEntity,player);
        }
        check(player);
    }

    @Override
    public void checkCollect(ItemStack itemStack, Player player) {
        for(AbstractMissionInfo missionInfo:missions)
        {
            missionInfo.checkCollect(itemStack,player);
        }

        check(player);
    }

    @Override
    public void checkPosition(BlockPos blockPos, Player player) {
        for(AbstractMissionInfo missionInfo:missions)
        {
            missionInfo.checkPosition(blockPos,player);
        }

        check(player);
    }

    /**
     * 保存主任务的具体内容，包括奖励信息和子任务列表
     */
    @Override
    protected CompoundTag saveMissionContentPack() {
        CompoundTag contentPack = new CompoundTag();

        // 保存奖励信息
        if (rewardInfo != null) {
            contentPack.put("reward", rewardInfo.saveToNBT());
        }

        // 保存子任务列表
        ListTag missionsList = new ListTag();
        for (AbstractMissionInfo mission : missions) {
            missionsList.add(mission.getModPack());
        }
        contentPack.put("missions", missionsList);

        return contentPack;
    }

    /**
     * 加载主任务的具体内容，包括奖励信息和子任务列表
     */
    @Override
    protected void loadMissionContentPack(CompoundTag missionContentPack) {
        // 加载奖励信息
        if (missionContentPack.contains("reward")) {
            CompoundTag rewardTag = missionContentPack.getCompound("reward");
            this.rewardInfo = RewardInfo.loadFromNBT(rewardTag);
        }

        // 加载子任务列表
        if (missionContentPack.contains("missions")) {
            ListTag missionsList = missionContentPack.getList("missions", 10); // 10 = CompoundTag
            this.missions = new ArrayList<>();

            for (int i = 0; i < missionsList.size(); i++) {
                CompoundTag missionTag = missionsList.getCompound(i);
                AbstractMissionInfo mission = createMissionFromNBT(missionTag);
                if (mission != null) {
                    this.missions.add(mission);
                }
            }

            // 更新目标数量为子任务数量
            setGoal(this.missions.size());
        }
    }

    /**
     * 从NBT数据创建任务实例
     * 这是一个简化的实现，实际使用时可能需要更复杂的任务类型识别和创建逻辑
     */
    private AbstractMissionInfo createMissionFromNBT(CompoundTag missionTag) {
        // 这里需要根据任务类型创建相应的任务实例
        // 这是一个示例实现，您需要根据实际的任务类型系统进行调整

        if (!missionTag.contains("age_right")) {
            return null;
        }

        CompoundTag ageRightTag = missionTag.getCompound("age_right");
        if (!ageRightTag.contains("mission")) {
            return null;
        }

        CompoundTag missionDataTag = ageRightTag.getCompound("mission");

        // 获取第一个任务键（假设每个CompoundTag只有一个任务）
        String missionKey = null;
        for (String key : missionDataTag.getAllKeys()) {
            missionKey = key;
            break;
        }

        if (missionKey == null) {
            return null;
        }

        CompoundTag missionData = missionDataTag.getCompound(missionKey);

        // 根据任务类型创建相应的任务实例
        // 这里需要您根据实际的任务系统来实现
        // 例如：
        // if (missionKey.startsWith("kill")) {
        //     return new KillMissionInfo(missionData);
        // } else if (missionKey.startsWith("collect")) {
        //     return new CollectMissionInfo(missionData);
        // } else if (missionKey.startsWith("position")) {
        //     return new PositionMissionInfo(missionData);
        // }

        // 根据任务类型创建相应的任务实例
        if (missionData.contains("type")) {
            try {
                MissionType type = MissionType.valueOf(missionData.getString("type"));

                switch (type) {
                    case KILL:
                        KillMissionInfo killMission = new KillMissionInfo();
                        killMission.loadFromModPack(missionTag);
                        return killMission;
                    // ... 其他任务类型 ...
                    case MAIN:
                        MainMissionInfo mainMission = new MainMissionInfo();
                        mainMission.loadFromModPack(missionTag);
                        return mainMission;
                    default:
                        break;
                }
            } catch (IllegalArgumentException e) {
                // 类型不存在
            }
        }

//        return null;
        return null; // 暂时返回null，需要您根据实际情况实现
    }
}